package com.hitqz.robot.daemon.quartz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.hitqz.robot.api.business.entity.GoodsBuffersEntity;
import com.hitqz.robot.api.business.entity.GoodsGroupEntity;
import com.hitqz.robot.biz.service.GoodsBuffersService;
import com.hitqz.robot.biz.service.GoodsGroupService;
import com.hitqz.robot.daemon.quartz.model.AgvCallDataDto;
import com.hitqz.robot.daemon.quartz.model.AgvCallResult;
import com.hitqz.robot.daemon.quartz.service.AgvStoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author xupkun
 * @date 2025/5/7
 */
//@Service
@RequiredArgsConstructor
@Slf4j
@Deprecated
public class AgvStoreServiceImpl implements AgvStoreService {

    private final GoodsBuffersService goodsBuffersService;

    private final GoodsGroupService goodsGroupService;


    @Override
    public List<GoodsBuffersEntity> findBestPlace(String src, String des, Integer num, String zx, Integer srcPlace, List<AgvCallDataDto> storeData) {
        String realStoreName = findZxBySrc(src, des, srcPlace);
        log.info("根据地点查询 {} -- {}--- zx:{} realStoreName: {}", src, des, zx, realStoreName);
        List<GoodsGroupEntity> goodsGroupEntities = Optional.ofNullable(goodsGroupService.list()).orElse(Collections.emptyList());
        List<GoodsBuffersEntity> goodsBuffersEntities = Lists.newArrayList();
        List<GoodsBuffersEntity> startBuffer = Lists.newArrayList();
        GoodsBuffersEntity targetBuffer = null;
        GoodsBuffersEntity previousBuffer = null;
        if ("911017".equals(src)) {
            String[] names = realStoreName.split("/");
            for (String name : names) {
                if (name.equals("旧轴")) {
                    // 旧轴优先从8-2开始搜索，优先拿旧轴。没有才拿返修
                    goodsGroupEntities = CollectionUtil.reverse(goodsGroupEntities);
                }
                for (GoodsGroupEntity goodsGroupEntity : goodsGroupEntities) {
                    //取的时候从8-2开始搜索，优先从8-2的方向开始拿, 优先拿旧轴
                    List<GoodsBuffersEntity> list = Optional.ofNullable(
                            goodsBuffersService.list(
                                    Wrappers.<GoodsBuffersEntity>lambdaQuery()
                                            .like(GoodsBuffersEntity::getName, "-1")
                                            .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                                            .eq(GoodsBuffersEntity::getRealStoreName, name)
                                            .eq(StrUtil.isNotEmpty(zx), GoodsBuffersEntity::getStoreName, zx)
                                            .orderByDesc(GoodsBuffersEntity::getId)
                            )
                    ).orElse(Collections.emptyList());
                    if (list.isEmpty()) {
                        continue;
                    }
                    targetBuffer = list.get(0);
                    List<GoodsBuffersEntity> allGoods = Optional.ofNullable(
                            goodsBuffersService.list(
                                    Wrappers.<GoodsBuffersEntity>lambdaQuery()
                                            .eq(GoodsBuffersEntity::getGroupId, targetBuffer.getGroupId())
                                            .eq(GoodsBuffersEntity::getStoreStatus, 0)
                                            //.eq(GoodsBuffersEntity::getRealStoreName, name)
                                            .orderByDesc(GoodsBuffersEntity::getSn)
                            )
                    ).orElse(Collections.emptyList());
                    if (num > allGoods.size()) {
                        //log.info("缓存区{} 没有缓存可以取，查询下一个", allGoods.get(0).getName());
                        previousBuffer = targetBuffer;
                        targetBuffer = null;
                        continue;
                    }
                    goodsBuffersEntities = allGoods;
                    break;
                }
            }
            // 由于可能某个架子数据不足，但是其他缓存架的数量是足够的，优先开始取数量充足的，下面是重新查询，能拿几个是几个
            if (targetBuffer == null && previousBuffer != null) {
                List<GoodsBuffersEntity> allGoods = Optional.ofNullable(
                        goodsBuffersService.list(
                                Wrappers.<GoodsBuffersEntity>lambdaQuery()
                                        .eq(GoodsBuffersEntity::getGroupId, previousBuffer.getGroupId())
                                        .eq(GoodsBuffersEntity::getStoreStatus, 0)
                        )
                ).orElse(Collections.emptyList());
                goodsBuffersEntities = allGoods;
                num = Math.min(num, goodsBuffersEntities.size());
            }
            if (!goodsBuffersEntities.isEmpty()) {
                GoodsBuffersEntity selected = goodsBuffersEntities.get(Math.max(0, num - 1));
                log.info("查询取的架子是：{}", selected.getName());
                int actualNum = Math.min(num, goodsBuffersEntities.size());
                for (int i = 0; i < actualNum; i++) {
                    GoodsBuffersEntity saveGood = goodsBuffersEntities.get(i);
                    try {
                        startBuffer.add(saveGood);
                        //AgvCallDataDto agvCallDataDto = JSONObject.parseObject(saveGood.getStoreData(), AgvCallDataDto.class);
                        saveGood.setStoreStatus(2);
                        if (StrUtil.isNotEmpty(zx)) {
                            saveGood.setStoreName("");
                        }
                        goodsBuffersService.updateById(saveGood);
                    } catch (Exception e) {
                        log.error("解析 storeData 出错，goodsId={}", saveGood.getId(), e);
                    }
                }
                startBuffer = CollectionUtil.reverse(startBuffer);
            }

        } else if ("911017".equals(des)) {
            // TODO 实现从缓存架取的逻辑

            String[] names = realStoreName.split("/");
            for (String name : names) {
                if (name.equals("返修")) {
                    // 饭修优先从8-2开始搜索
                    goodsGroupEntities = CollectionUtil.reverse(goodsGroupEntities);
                }
                for (GoodsGroupEntity goodsGroupEntity: goodsGroupEntities) {
                    GoodsBuffersEntity startGroupName = null;
                    if ((name.equals("旧轴") || name.equals("返修") )&& goodsGroupEntity.getName().equals("分组1")) {
                        // 如果是第一组的话 固定放报废
                        continue;
                    }
                    List<GoodsBuffersEntity> list = Optional.ofNullable(
                            goodsBuffersService.list(
                                    Wrappers.<GoodsBuffersEntity>lambdaQuery()
                                            .like(GoodsBuffersEntity::getName, "-1")
                                            .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                                            .eq(GoodsBuffersEntity::getRealStoreName, name)
                                            .eq(StrUtil.isNotEmpty(zx), GoodsBuffersEntity::getStoreName, zx)
                                            .orderByDesc(GoodsBuffersEntity::getId)
                            )
                    ).orElse(Collections.emptyList());
                    if (list.isEmpty()) {
                        list = goodsBuffersService.list(
                                Wrappers.<GoodsBuffersEntity>lambdaQuery().
                                        like(GoodsBuffersEntity::getName, "-1")
                                        .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                        );
                    }
                    Optional<GoodsBuffersEntity> goodsBuffersEntity =
                            list.stream().filter(t->
                                    name.equals(t.getRealStoreName())).findFirst();
                    if (goodsBuffersEntity.isPresent()) {
                        startGroupName = goodsBuffersEntity.get();
                        List<GoodsBuffersEntity> allGoods = goodsBuffersService.list(
                                Wrappers.<GoodsBuffersEntity>lambdaQuery().eq(GoodsBuffersEntity::getGroupId, startGroupName.getGroupId())
                                        .eq(GoodsBuffersEntity::getStoreStatus, 1)
                        );
                        if (num > allGoods.size()) {
                            //log.info("缓存区没有缓存可以放，取查询下一个");
                            startGroupName = null;
                            continue;
                        }
                        goodsBuffersEntities = allGoods;
                    } else {
                        goodsBuffersEntity =
                                list.stream().filter(t->
                                        t.getStoreStatus().equals(1)).findFirst();
                        if (goodsBuffersEntity.isPresent()) {
                            startGroupName = goodsBuffersEntity.get();
                            List<GoodsBuffersEntity> allGoods = goodsBuffersService.list(
                                    Wrappers.<GoodsBuffersEntity>lambdaQuery().eq(GoodsBuffersEntity::getGroupId, startGroupName.getGroupId())
                                            .eq(GoodsBuffersEntity::getStoreStatus, 1)
                            );
                            if (num > allGoods.size()) {
                                //log.info("缓存区没有缓存可以放，取查询下一个");
                                startGroupName = null;
                                continue;
                            }
                            goodsBuffersEntities = allGoods;
                        }
                    }
                    if (startGroupName != null) {
                        // 更新第一更 单开一列
                        startGroupName.setStoreName(zx);
                        startGroupName.setRealStoreName(name);
                        goodsBuffersService.updateById(startGroupName);
                        break;
                    }
                }

                if(!goodsBuffersEntities.isEmpty()) {
                    GoodsBuffersEntity goodsBuffersEntity = goodsBuffersEntities.get(0);
                    log.info("查询存放的架子是：" + goodsBuffersEntity.getName());
                    for (int i = 0; i < num; i++) {
                        GoodsBuffersEntity saveGood = goodsBuffersEntities.get(i);
                        if (!storeData.isEmpty()) {
                            AgvCallDataDto agvCallDataDto = storeData.get(i);
                            agvCallDataDto.setPos(saveGood.getName());
                            saveGood.setStoreData(JSONObject.toJSONString(agvCallDataDto));
                        }
                        startBuffer.add(saveGood);
                        // 预计存放
                        saveGood.setStoreName(zx);
                        saveGood.setRealStoreName(name);
                        saveGood.setStoreStatus(3);
                        goodsBuffersService.updateById(saveGood);
                    }
                }
            }
        }

        return startBuffer;
    }



    private String findZxBySrc(String src, String des, Integer srcPlace) {
        String zx = "";
        if (srcPlace == 1) {
            zx = "旧轴";
        } else if (srcPlace == 2) {
            zx = "返修";
        } else if (srcPlace == 3) {
            zx = "报废";
        }
        if(StrUtil.isNotBlank(zx)) {
            return zx;
        }
        if ((src.equals("911005") || src.equals("911022"))&& des.equals("911017")) {
            // 报废直接下线
            zx = "报废";
            return zx;
        }
        if(des.equals("911017")) {
            // 目标点是缓存架
            if (src.equals("911006") || src.equals("911021")) {
                zx = "返修";
            } else if (src.equals("91102") ) {
                zx = "旧轴";
            }
        }
        if (src.equals("911017") && des.equals("911012")) {
            // 缓存上线
            zx = "旧轴/返修";
        }
        return zx;
    }

}
